//
//  GeneralStoreTesting.m
//  atomicstore
//
//  Created by Stephan Zehrer on 02.03.11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//


#import "GeneralStoreTesting.h"
#import "XMLDocumentStore.h"

#import "XMLTools.h"


@implementation GeneralStoreTesting


- (void)setUp {
    //[super setUp];
    NSArray *bundles = [NSArray arrayWithObject:[NSBundle bundleForClass:[GeneralStoreTesting self]]];
	
    model = [[NSManagedObjectModel mergedModelFromBundles:bundles] retain];
    
	coordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];
	
}


- (void)tearDown {
    //[super tearDown];
    [model release];
    model = nil;
    [coordinator release];
    coordinator = nil;
    
    if (fileURL != nil) {
		//NSFileManager *fileManager = [NSFileManager defaultManager];
		//NSError *error = nil;
		
		//if (![fileManager removeItemAtURL:fileURL error:&error]) {
		//	NSLog (@"Proble to delete the file");
		//}
		// STAssertTrue(success, @"Couldn't delete test file after test run");
		[fileURL release];
		fileURL = nil;
    }
}

//@"XMLDocumentStore"
// NSXMLStoreType

- (void)testStore {
	XMLStore *store = [self addTestStoreToCoordinator:coordinator withStoreType:@"XMLDocumentStore"];
	NSManagedObjectContext *context = [[NSManagedObjectContext alloc] init];
	[context setPersistentStoreCoordinator:coordinator];
	
	NSEntityDescription *entity = [NSEntityDescription entityForName:@"TestingEntity" inManagedObjectContext:context];

	[store setRootEntityType:entity];
	
	
    id testObject = [[NSManagedObject alloc] initWithEntity:entity insertIntoManagedObjectContext:context];
	
	NSData *testData = [@"binary test data" dataUsingEncoding:NSASCIIStringEncoding];
    [testObject setValue:testData forKey:@"binaryValue"];
    
    NSNumber *testBoolValue = [NSNumber numberWithBool:1];
    [testObject setValue:testBoolValue forKey:@"boolValue"];
	
    NSDate *testDateValue = [NSDate dateWithNaturalLanguageString:@"10/10/2006"];
    [testObject setValue:testDateValue forKey:@"dateValue"];
  
    NSDecimalNumber *testDecimal = [NSDecimalNumber decimalNumberWithString:@"10.5"];
    [testObject setValue:testDecimal forKey:@"decimalValue"];
    
    NSNumber *testDoubleValue = [NSNumber numberWithDouble:5.005];
    [testObject setValue:testDoubleValue forKey:@"doubleValue"];
    
    NSNumber *testFloatValue = [NSNumber numberWithFloat:0.005];
    [testObject setValue:testFloatValue forKey:@"floatValue"];
    
    NSNumber *testIntValue = [NSNumber numberWithInt:50];
    [testObject setValue:testIntValue forKey:@"intValue"];
    
    NSNumber *testLongValue = [NSNumber numberWithLong:500];
    [testObject setValue:testLongValue forKey:@"longValue"];
    
    NSNumber *testShortValue = [NSNumber numberWithShort:5];
    [testObject setValue:testShortValue forKey:@"shortValue"];
    
    NSString *testStringValue = @"test string value";
    [testObject setValue:testStringValue forKey:@"stringValue"];
    
  
    [testObject setValue:@"test transient string value" forKey:@"transientString"];
	
	
    NSError *error = nil;
	[context save:&error];
	
}


- (void)testXMLRead {
	
	NSURL *url = [NSURL fileURLWithPath:@"/var/folders/UX/UXM3OnbQGW83FDKvemndRU+++TI/-Tmp-/_XMLStoreFile.xml"];
	//NSURL *url = [NSURL fileURLWithPath:@"/Users/steve/Temporary/newTest.xml"];
	
	NSError *error = nil;
	
	NSInteger options = NSXMLNodePreserveCharacterReferences | NSXMLNodePreserveWhitespace;
	
	//[[NSFileManager defaultManager] createFileAtPath:[url path] contents:nil attributes:nil];
	
	NSXMLDocument *document = [[NSXMLDocument alloc] initWithContentsOfURL:url options:options error:&error];
	
	NSXMLNode *aNode = [document rootElement];
	
	//NSXMLNodeKind
	do {
		if (( [aNode kind] == NSXMLElementKind ) && ([aNode attributeForName:@"id"] != nil)) {
		  NSLog(@"<%@ %@/>",[aNode name],[aNode attributeForName:@"id"]);
		}
	} while (aNode = [aNode nextNode]);
	
	/*
	for (NSXMLElement *element in [node children]) {
		NSLog(@"<%@> %@ </%@>",[element name],[element objectValue], [element name]);
		
		for (NSXMLNode *att in [element attributes]) {
			id objVal = [att objectValue];
			NSLog(@"  Attribute: %@ Value: %@",[att name],objVal);
		}
	}	
	
	
	
	for (NSXMLElement *node in [document children]) {
		NSLog(@"Node Kinde: %i Value: %@",[node kind],[node stringValue]);
		
		if ([node kind] == NSXMLProcessingInstructionKind){
			[node detach];
		} 
	}
	
	NSLog(@"Root Element: %@",[[document rootElement]stringValue]);
	
	*/
	/*
	NSXMLDocument *document = [[NSXMLDocument alloc] initWithKind:NSXMLDocumentXMLKind options:options];
	
	
	[document setVersion:@"1.1"];
	[document setCharacterEncoding:@"UTF-8"];
		
	//NSXMLElement *node =[[NSXMLElement alloc] initWithName:@"object" stringValue:@"test"];

	NSXMLElement *rootNode =[[NSXMLElement alloc] initWithName:@"object" stringValue:@"test"];
	//[document setRootElement:rootNode];
	
	
	
	NSXMLNode *node =[NSXMLNode processingInstructionWithName:@"NSStoreModelVersionIdentifiers" stringValue:@"()"];
	[document insertChild:node atIndex:0];
	[document insertChild:rootNode atIndex:1];
	
	[node release];
	[rootNode release];
	
	NSData* data = [document XMLData];
	
	[data writeToURL:url atomically:YES];
	
	 
	[document release];
	 */
}


- (void)testXMLWrite {
	//NSURL *url = [NSURL fileURLWithPath:@"/var/folders/UX/UXM3OnbQGW83FDKvemndRU+++TI/-Tmp-/_XMLStoreFile.xml"];
	NSURL *url = [NSURL fileURLWithPath:@"/Users/steve/Temporary/newTest.xml"];
	
	NSInteger options = NSXMLNodePreserveCharacterReferences | NSXMLNodePreserveWhitespace;
	
	NSXMLDocument *doc = [[NSXMLDocument alloc] initWithKind:NSXMLDocumentXMLKind options:options];
	[doc setVersion:@"1.1"];
	[doc setCharacterEncoding:@"UTF-8"];

	NSXMLElement *root = [doc addChildElementWithName:@"data"];
	
	[root addChildElementWithName:@"location" id:@"1"];
	[root addChildElementWithName:@"location" id:@"2"];
	[root addChildElementWithName:@"location" id:@"3"];
	
	NSXMLElement *tour = [root addChildElementWithName:@"tour"];
	//NSXMLElement *points = [tour addChildElementWithName:@"points"];
	NSXMLNode	*refs = [tour addAttributeWithName:@"idrefs" stringValue:@""];
	id idrefs = [NSArray arrayWithObjects:@"1", @"2", @"3"];
	[refs setObjectValue:idrefs];
	
	
	NSData *data = [doc XMLDataWithOptions:NSXMLNodePrettyPrint];
	[data writeToURL:url atomically:YES];

}



// Store Types are e.g. NSSQLiteStoreType, NSXMLStoreType
- (id)addTestStoreToCoordinator:(NSPersistentStoreCoordinator *)psc withStoreType:(NSString *)storeType {
	
	NSFileManager *fileManager = [NSFileManager defaultManager];
	NSString *basePath = NSTemporaryDirectory();	
	
	NSString *filePath = [basePath stringByAppendingPathComponent:@"_XMLStoreFile.xml"];
	
	/*
	while ([fileManager fileExistsAtPath:filePath]) {
		filePath = [basePath stringByAppendingPathComponent:[NSString stringWithFormat:@"_XMLStoreFile%d.xml", rand()]];
	}
	*/
	
	NSLog(@"File: %@",filePath);
	
	fileURL = [NSURL fileURLWithPath:filePath];
	
	NSError *error = nil;
	[[NSFileManager defaultManager] removeItemAtURL:fileURL error:&error];
	
    NSPersistentStore *store = [psc addPersistentStoreWithType:storeType configuration:nil URL:fileURL options:nil error:nil];        
	
	return store;
}

@end
